package com.chaodroid.flyui.view.viewpager.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by CHEN on 2018/1/16.
 */

public abstract class FlyFragmentPagerStateAdapter extends FragmentStatePagerAdapter {

    private int mFragmentCount = 0;
    private List<Fragment> mFragments = null;
    private List<String> mTitles = null;

    public FlyFragmentPagerStateAdapter(FragmentManager fm, int fragmentCount, List<String> titles) {
        super(fm);
        mFragmentCount = fragmentCount;
        mFragments = new ArrayList<>(fragmentCount);
        mTitles = titles;
    }

    public FlyFragmentPagerStateAdapter(FragmentManager fm, int fragmentCount, String[] titles) {
        this(fm, fragmentCount, Arrays.asList(titles));
    }

    @Override
    public int getCount() {
        return mFragmentCount;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        if (mFragments != null) {
            //懒加载
            fragment = mFragments.get(position);
            if (fragment == null) {
                fragment = newFragmentInstance(position);
            }
        }
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles == null ? null : mTitles.get(position);
    }

    /**
     * getItemPosition() 函数，返回 POSITION_NONE
     * FragmentStatePagerAdapter:
     * 会因 POSITION_NONE 触发调用 destroyItem() 真正的释放资源，重新建立一个新的 Fragment
     * FragmentPagerAdapter:
     * 仅仅会在 destroyItem() 中 detach 这个 Fragment，
     * 在 instantiateItem() 时会使用旧的 Fragment，并触发 attach，因此没有释放资源及重建的过程。
     * @param object
     * @return
     */
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    abstract public Fragment newFragmentInstance(int position);
}
